require 'ruport/acts_as_reportable'

class ActiveReportAction < WorkflowAction  
  validates_inclusion_of :format, :in => [:csv, :html, :pdf, :native]
  
  def valid_input_classes
    [ActiveRecord::Base]
  end

  def output_class
    format == :native ? Ruport::Data::Table : String
  end
  
  def format
    options[:format] || :csv
  end
  
  def mime_type
    case format
    when :csv
      'text/csv'
    when :html
      'text/html'
    when :pdf
      'application/pdf'
    when :native
      nil
    end
  end
  
  def filename
    (options[:filename] || 'report') + ".#{extension}"
  end
  
  def extension
    (mime_type == :native) ? 'ruport' : format.to_s
  end
  
  def execute
    report = nil
    if input
      if input_class.respond_to?(:report_table)
        report = input_class.report_table(:all, 
          :conditions => { :id => input.collect(&:id) }
        )
      else
        report = Ruport::Data::Table.new(
          :column_names => input.first.attributes.keys
        )
        input.each { |obj| report << obj.attributes }
      end
      @output = (format == :native) ? report : report.as(format)
    end
  end  
end
